package com.candy.demo6;

import com.candy.jdbcutil.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 测试写好的工具类
 * 提供的是一个DataSource接口的数据源
 * QueryRunner类构造方法，接收DataS接口的实现类
 * 后面，调用方法update，query，无需传递他们Connection连接对象
 */
public class QueryRunnerDemo {
   //定义2个方法，实现数据表的添加，数据表查询
    //QueryRunner类对象，写在类成员位置
   public static void main(String[] args) {
        //insert();
       select();
   }
    private  static QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

   //数据表的查询
    public static void select(){
        String sql = "select * from tb_student";
        List<Object[]> list = null;
        try {
            list = qr.query(sql,new ArrayListHandler());

            for(Object[] objs:list){
                for(Object obj:objs){
                    System.out.print(obj+"  ");
                }
                System.out.println();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("数据查询失败");
        }
    }
   //数据表的添加数据
    public static void insert() {
        String sql = "insert into tb_student(tid,name) values(?,?)";
        Object[] params = {7,"晓童"};
        try {
            int row = qr.update(sql,params);
            System.out.println(row);
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new RuntimeException(("数据添加失败"));
        }
    }
}
